package com.schoolcloud.share.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolcloud.common.model.PageDTO;
import com.schoolcloud.common.util.UserContext;
import com.schoolcloud.share.dto.ShareVideoSaveDTO;
import com.schoolcloud.share.entity.*;
import com.schoolcloud.share.query.SetSectionQuery;
import com.schoolcloud.share.query.VideoQuery;
import com.schoolcloud.share.service.*;
import com.schoolcloud.share.mapper.VideosMapper;
import com.schoolcloud.share.vo.SectionVideoItem;
import com.schoolcloud.share.vo.SectionVideoVO;
import com.schoolcloud.share.vo.ShareVideoInfo;
import com.schoolcolud.daomybatisplus.dto.MpPageUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hongmizfb
 * @description 针对表【videos(视频主表)】的数据库操作Service实现
 * @createDate 2025-05-16 18:35:15
 */
@Service
@RequiredArgsConstructor
public class VideosServiceImpl extends ServiceImpl<VideosMapper, Videos>
        implements VideosService {
    private final VideoTagsService videoTagsService;
    private final VideoCategoriesService videoCategoriesService;
    private final CategoriesService categoriesService;
    private final SectionVideosService sectionVideosService;
    private final SetSectionsService setSectionsService;
    private final VideoSetsService videoSetsService;
    private final TagsService tagsService;

    @Override
    @Transactional
    public Videos createVideo(ShareVideoSaveDTO videos) {
        videos.setUserId(UserContext.getUserToInteger());
        videos.setCreateTime(LocalDateTime.now());
        save(videos);
        VideoCategories videoCategories = new VideoCategories();
        videoCategories.setVideoId(videos.getVideoId());
        videoCategories.setCategoryId(videos.getCategoryId());
        videoCategoriesService.save(videoCategories);
        videos.getTags().forEach(tagId -> {
            VideoTags videoTags = new VideoTags();
            videoTags.setVideoId(videos.getVideoId());
            videoTags.setTagId(tagId);
            videoTagsService.save(videoTags);
        });
        return videos;
    }

    @Override
    public PageDTO<Videos> getVideoPage(VideoQuery query) {
        String title = query.getTitle();
        String bucketName = query.getBucketName();
        String userId = query.getUserId();
        String excludeIdsStr = query.getExcludeIds();
        String[] excludeIds = null;
        if (StrUtil.isNotBlank(excludeIdsStr)) {
            excludeIds = query.getExcludeIds().split(",");
        }
        Page<Videos> page = lambdaQuery()
                .like(StrUtil.isNotBlank(title), Videos::getTitle, title)
                .eq(StrUtil.isNotBlank(userId), Videos::getUserId, userId)
                .notIn(excludeIds != null, Videos::getVideoId, (Object) excludeIds)
                .page(query.toMpPage());
        return MpPageUtil.of(page, Videos.class);
    }

    @Override
    public ShareVideoInfo getVideoInfo(Integer id) {
        /*后续考虑使用sql提高性能，而非多次单表查询*/
        ShareVideoInfo shareVideoInfo = new ShareVideoInfo();
        Videos byId = getById(id);
        BeanUtils.copyProperties(byId, shareVideoInfo);
        VideoCategories videoCategories = videoCategoriesService.getByVideoId(id);
        shareVideoInfo.setCategoryName(categoriesService.getById(videoCategories.getCategoryId()).getName());
        List<VideoTags> tags = videoTagsService.getListByVideoId(id);
        List<Tags> collect = tags.stream().map(item -> tagsService.getById(item.getTagId())).collect(Collectors.toList());
        shareVideoInfo.setTagList(collect);
        /*查询合集信息*/
//       视频与章节关联，章节表中有合集id，先从视频章节关联表中查询出章节id，然后再从章节信息中查询合集信息
        SectionVideos sectionVideos = sectionVideosService.getByVideoId(id);
        if (sectionVideos == null){
            return shareVideoInfo;
        }
        SetSections bySectionId = setSectionsService.getBySectionId(sectionVideos.getSectionId());
        //查询合集信息
        VideoSets videoSets = videoSetsService.getById(bySectionId.getSetId());
        shareVideoInfo.setVideoSets(videoSets);
        /*查询合集下的所有章节信息*/
        if (videoSets != null){
            List<SetSections> sectionVideosList = setSectionsService.getListBySetId(bySectionId.getSetId());
            shareVideoInfo.setSetSections(sectionVideosList);
        }
        return shareVideoInfo;
    }

    @Override
    public PageDTO<Videos> getNotRelationVideoList(VideoQuery query) {
        List<Videos> v = baseMapper.getNotRelationVideoList(query);
        long total = baseMapper.getNotRelationVideoCount(query);
        PageDTO<Videos> videosPageDTO = new PageDTO<>();
        videosPageDTO.setList(v);
        videosPageDTO.setTotal(total);
        return videosPageDTO;
    }
    public PageDTO<SectionVideoVO> getSetSectionsPage(SetSectionQuery query) {
        Page<SetSections> setSectionsPage = setSectionsService.getSetSectionsPage(query);
        PageDTO<SectionVideoVO> of = MpPageUtil.of(setSectionsPage, SectionVideoVO.class);
//        查询这些章节下关联的视频信息
        of.getList().forEach(sectionVideoVO -> {
            List<SectionVideoItem> collect =sectionVideosService.lambdaQuery().eq(SectionVideos::getSectionId, sectionVideoVO.getSectionId()).list()
                    .stream().map(item -> {
                        SectionVideoItem sectionVideoItem = new SectionVideoItem();
                        BeanUtils.copyProperties(item, sectionVideoItem);
                        Videos byId = getById(item.getVideoId());
                        BeanUtils.copyProperties(byId, sectionVideoItem);
                        return sectionVideoItem;
                    }).collect(Collectors.toList());
            sectionVideoVO.setVideos(collect);
        });
        return of;
    }
    @Override
    public List<SectionVideoItem> getSetSectionRelatedList(Integer sectionId) {
        return sectionVideosService.lambdaQuery().eq(SectionVideos::getSectionId, sectionId).list().stream().map(item -> {
            SectionVideoItem sectionVideoItem = new SectionVideoItem();
            BeanUtils.copyProperties(item, sectionVideoItem);
            Videos byId = getById(item.getVideoId());
            BeanUtils.copyProperties(byId, sectionVideoItem);
            return sectionVideoItem;
        }).collect(Collectors.toList());
    }
}
